/**
 * create by thanatos on 2015-09-02
 **/

var Category = require('./domain').Category
var Goods = require('./domain').Goods
var Selector = require('./domain').Selector
var Page = require('./domain').Page
var ObjectId = require('mongodb-core').BSON.ObjectID
var ISearcher = require('../api/api').ISearcher
var IGoods = require('../api/api').IGoods
var ICategory = require('../api/api').ICategory
var utils = require('./utils')
var config = require('../config')

module.exports = function (app) {

    /*--图标--*/
    app.get('/favicon.ico', function *() {
        this.response.redirect('/images/favicon.ico')
    })

    /*--index--*/
    app.get('/', function *() {
        var path = this.path
        yield this.render('index', {
            title: '西市',
            path: path
        })
    })

    /*--搜索--*/
    app.get('/search', function *() {
        var $self = this
        var path = $self.path
        var qr = $self.query.qr
        var cid = $self.query.cid
        var pageNum = $self.pageNum&&$self.pageNum || 1
        console.log('---------------search------qr--------', qr, '----------------')
        console.log('---------------search------cid-------', cid, '----------------')
        var values = {}
        var selector = new Selector()
        var products = []
        var query = ''
        var proAttr
        var item
        if(cid){
            query = 'cid=' + cid
            values = yield IGoods.findByCategory(parseInt(cid))
            values = JSON.parse(values)
            selector.selected.category = values.category
            products = values.products || []
            for (var i in products) {
                proAttr = yield this.mongo.collection('ProductAttribute').findOne({pid: products[i].id})
                products[i].keywords = products[i].keywords.split(',')
                products[i].attributes = proAttr.attributes
                selector.merge(proAttr.attributes)
            }
        }else{
            query = 'qr=' + qr
            values = yield ISearcher.searcher(utils.trimspace(qr), 1)
            values = JSON.parse(values)
            products = values.products || []
            for (var i in products) {
                item = values.results[i]
                products[i].highlightTitle = item.title
                products[i].keywords = item.keywords.split(',')
                proAttr = yield this.mongo.collection('ProductAttribute').findOne({pid: products[i].id})
                products[i].attributes = proAttr && proAttr.attributes || {}
                selector.merge(products[i].attributes)
                if(!$self.session.histories){
                    $self.session.$set('histories', [qr])
                }else{
                    if($self.session.histories.indexOf(qr)==-1)
                        $self.session.$push('histories', qr)
                }
            }
        }
        console.log('search over >>>>>>')

        selector.resort()

        //品牌的拼音首字母
        var brands = selector.attributes['品牌']
        if(brands){
            var arr = []
            for(var i=0; i<brands.length; i++){
                item = brands[i]
                var xchar = yield ISearcher.pinyin(item)
                console.log('xchar>>>', xchar.toUpperCase())
                arr.push({xchar:xchar.toUpperCase(), value:item})
            }
            selector.attributes['品牌'] = arr
        }

        var count = products.length

        $self.session.$set('products', products)
        $self.session.$set('selector', selector)
        var page = new Page(pageNum, config.PAGE_SIZE, products.length, products.slice((pageNum-1)*config.PAGE_SIZE, pageNum*config.PAGE_SIZE))
        yield $self.render('search', {
            title: '搜索',
            path: path,
            count: count,
            qr: qr,
            page: page,
            selector: selector,
            query: query,
            merge4params: utils.merge4params
        })
    })

    /*--属性刷选--*/
    app.get('/search/attribute/filter', function *() {
        var $self = this

        var selector = new Selector()
        var results = []
        var products = []
        var pipe = []

        console.log('/search/attribute/filter >>> ', $self.query)

        //将url参数规范成对象
        var params = utils.params2obj($self.query)
        var pageNum = params.pageNum&&parseInt(params.pageNum) || 1

        //$unwind
        pipe.push({$unwind:"$products"})

        var match = {
            $match: {
                "_id": $self.session.id
            }
        }
        pipe.push(match)

        console.log('/search/attribute/filter>>>params.selected>>> ', params.selected)

        if (params.selected) {
            selector.selected = new Selector.Selected(params.selected)
            var elements = ['products', 'attributes']

            //match attributes
            if(selector.selected.attributes){
                for (var key in params.selected.attributes) {
                    //make sure that it is a array object
                    var ins = [].concat(params.selected.attributes[key])
                    match.$match[elements.concat(key).join('.')] = {$in:ins}
                }
            }

            //price
            if(selector.selected.price){
                var mp = {}
                if(+selector.selected.price.start){
                    mp.$gte = +selector.selected.price.start
                }
                if(+selector.selected.price.end){
                    mp.$lte = +selector.selected.price.end
                }
                match.$match['products.price'] = mp
            }

            //sort
            if(selector.selected.sort){
                //selector.selected.sort = selector.selected.sort[0]
                switch(selector.selected.sort){
                    case 'new':
                        console.log('sort>>>new')
                        pipe.push({$sort:{"products.createOn":-1}})
                        break

                    case 'popular':
                        pipe.push({$sort:{"products.comment":-1}})
                        break

                    case 'sale':
                        break
                }
            }
        }

        //$project
        pipe.push({$project:{products:1,_id:0}})

        results = yield this.mongo.collection('session').aggregate(pipe).toArray()

        results.forEach(function (item) {
            products.push(item.products)
        })

        products.forEach(function (item) {
            selector.merge(item.attributes)
        })
        selector.resort()

        console.log('attributes filter selector >>>', selector)
        var query
        if($self.query.cid){
            query = 'cid=' + $self.query.cid
            selector.selected.category = $self.session.selector.selected.category
        }else{
            query = 'qr=' + $self.query.qr
        }

        //品牌的拼音首字母
        var brands = selector.attributes && selector.attributes['品牌'] || undefined
        if(brands){
            var arr = []
            for(var i=0; i<brands.length; i++){
                var item = brands[i]
                var xchar = yield ISearcher.pinyin(item)
                arr.push({xchar:xchar.toUpperCase(), value:item})
            }
            selector.attributes['品牌'] = arr
        }

        var page = new Page(pageNum, config.PAGE_SIZE, products.length, products.slice((pageNum-1)*config.PAGE_SIZE, pageNum*config.PAGE_SIZE))

        yield this.render('search', {
            title: '搜索',
            path: $self.path,
            count: products.length,
            qr: $self.query.qr,
            query: query,
            page: page,
            selector: selector,
            merge4params: utils.merge4params
        })
    })

    /*--商品分类--*/
    app.get('/catalog', function *() {
        var $self = this
        console.log("catalog >>>>>")
        var catalogs = yield ICategory.findTop()
        console.log('<<<<<catalog')
        catalogs = JSON.parse(catalogs)
        console.log(catalogs)
        yield this.render('category', {
            title: '商品分类',
            catalogs: catalogs,
            path: $self.path
        })
    })

    app.get('/main/catalog', function *() {
        var $self = this
        var categories = {
            '家用电器': [2562],
            '手机、数码': [3098, 3126],
            '电脑、办公': [2656],
            '家居、家具、家厨': [3187, 3245],
            '男装、女装、内衣、珠宝': [3295, 3509],
            '个护化妆': [2751],
            '鞋靴、箱包、钟表、奢侈品': [3411, 3449, 2821],
            '户外运动': [3577],
            '汽车、汽车用品': [2970],
            '母婴、玩具乐器': [2828, 3035],
            '食品、酒类、生鲜、特产': [2910],
            '营养保健': [2910],
            '图书、音像、电子书': [2489],
            '彩票、旅行、充值、票务': [3690]
        }

        for(var key in categories){
            var children = []
            for(var i in categories[key]){
                var results = yield ICategory.findChildrenByParent(categories[key][i])
                results = JSON.parse(results)
                children = children.concat(results)
            }
            categories[key] = children
        }

        $self.body = {
            categories: categories
        }
    })

    /*--查看某分类的信息--*/
    app.get('/catalog/show', function *() {
        var _id = this.query._id
        var catalog = yield this.mongo.collection('category').findOne({_id: ObjectId(_id)})
        yield this.render('catalog_show', {
            catalog: catalog
        })
    })

    /*--添加商品--*/
    app.post('/goods/add', function *() {
        var $self = this
        var form = $self.request.query
        form = utils.params2obj(form)
        var goods = new Goods(form)
        var pid = yield IGoods.save(JSON.stringify(goods))
        yield $self.mongo.collection('ProductAttribute').insertOne({pid: pid, attributes: form.attributes})
        yield $self.render('success', {
            message: '添加商品成功'
        })
    })

    /*--智能提示--*/
    app.get('/suggest', function *() {
        var $self = this
        var value = this.query.field
        console.log(value)
        var suggests = yield ISearcher.suggest(value, 10)
        console.log('-----------')
        var results = []
        for (var i in suggests) {
            var map = suggests[i].split(',')
            var ish = $self.session.histories && $self.session.histories.indexOf(map[0])!=-1 || false
            results.push({
                field: map[0],
                count: parseInt(map[1]),
                ish: ish
            })
        }
        //快速排序
        var quickSort = function (arr, begin, end) {
            if(begin>=end)
                return
            var b = begin
            var e = end
            var sentry = arr[begin]
            while(begin<end){
                while(begin<end && arr[end].count<=sentry.count) --end
                arr[begin] = arr[end]
                while(begin<end && arr[begin].count>sentry.count) ++begin
                arr[end] = arr[begin]
            }
            arr[begin] = sentry
            quickSort(arr, b, begin-1)
            quickSort(arr, begin+1, e)
        }
        quickSort(results, 0, results.length-1)
        console.log('===============')
        this.body = {
            suggests: results
        }
    })

    /*--商品详情--*/
    app.get('/goods/details/:pid', function *() {
        var $self = this
        var pid = $self.params.pid
        if(!pid){
            yield $self.render('error/404', {
                message: '你要的商品没有找到'
            })
            return
        }
        var goods = yield IGoods.findOne(parseInt(pid))
        goods = JSON.parse(goods)
        if(!goods){
            yield $self.render('error/404', {
                message: '你要的商品没有找到哦'
            })
            return
        }
        var proAttr = yield this.mongo.collection('ProductAttribute').findOne({pid: goods.id})
        goods.attributes = {
            '商品名称': goods.title,
            '商品品牌': goods.brand,
            '商品编号': goods.label,
            '上架时间': goods.createOn
        }
        proAttr = proAttr && proAttr.attributes || {}
        for(var key in proAttr){
            goods.attributes[key] = proAttr[key]
        }
        goods.images = goods.images.split(',')
        yield $self.render('goods', {
            title: goods.title,
            goods: goods
        })
    })

    /*--添加商品分类--*/
    app.post('/category/add', function *() {
        var $self = this
        var form = $self.query
        var category = utils.params2obj(form)
        yield ICategory.save(JSON.stringify(category))
        yield $self.render('success', {
            message: '添加商品分类成功'
        })
    })

    app.post('/goods/delete', function *() {
        var $self = this
        var id = $self.request.body.id && parseInt($self.request.body.id) || undefined
        console.log('>>>>>', id)
        if(!id){
            yield $self.render('error/404', {message: '你操作的商品不存在'})
            return
        }
        try{
            yield IGoods.deleteOne(id)
            yield $self.mongo.collection('ProductAttribute').deleteOne({pid:id})
            yield $self.render('success', {message: '恭喜你中奖啦！！'})
        }catch(err){
            throw TypeError(500)
        }
    })

    app.get('/exchange/category', function *() {
        var $self = this
        console.log('exchange.category>>>>>')
        var catalogs = yield $self.mongo.collection('category').find({parent: {$exists: false}}).toArray()
        for (var i in catalogs) {
            var item = catalogs[i]
            var pid0 = yield ICategory.save(JSON.stringify({name: item.name, level: 1}))
            pid0 = parseInt(pid0)
            for (var j in item.children) {
                var sec = item.children[j]
                var pid1 = yield ICategory.save(JSON.stringify({name: sec.name, level: 2, parent: {id: pid0}}))
                pid1 = parseInt(pid1)
                for (var n in sec.children) {
                    var thir = sec.children[n]
                    yield ICategory.save(JSON.stringify({name: thir.name, level: 3, parent: {id: pid1}}))
                }
            }
        }
        yield $self.render('success', {
            message: '交换成功!'
        })
    })

    app.get('/exchange/goods', function *() {
        var $self = this
        var fs = require('fs')
        //var iconv = require('iconv-lite')
        var base = '/home/thanatos/Documents/Project/westmarket/京东-补全'
        fs.readdir(base, function (err, files) {
            files.forEach(function (file) {
                //file --> /补全/女装
                fs.readdir([base, file].join('/'), function (_err, _files) {
                    _files.forEach(function (_file) {
                        //_file --> /补全/女装/衬衫
                        fs.readdir([base, file, _file].join('/'), function (__err, __files) {
                            __files.forEach(function (__file) {
                                //__file --> /补全/女装/衬衫/0.json
                                try{
                                    var pid;
                                    switch(file){
                                        case '女装':
                                            pid = 3296
                                            break
                                        case '服饰配件':
                                            pid = 3382
                                            break
                                        case '内衣':
                                            pid = 3359
                                            break
                                        case '男装':
                                            pid = 3330
                                            break
                                    }
                                    var text = fs.readFileSync([base, file, _file, __file].join('/'))
                                    //text = iconv.decode(text, 'GBK')
                                    var goods = JSON.parse(text)
                                    var attributes = {}
                                    attributes['品牌'] = goods.brand
                                    goods.attributes.forEach(function (item) {
                                        attributes[item.name] = item.value
                                    })
                                    goods.attributes = attributes
                                    if (goods.keywords instanceof Array) {
                                        goods.keywords = goods.keywords.join(',')
                                    }
                                    if (goods.statistics) {
                                        goods.comment = goods.statistics.comment
                                        delete  goods.statistics
                                    }
                                    goods.createOn = goods.publishTime
                                    delete goods.publishTime
                                    for (var i in goods.images) {
                                        if (goods.images[i].startsWith('//')) {
                                            goods.images[i] = 'http:' + goods.images[i]
                                        }
                                    }
                                    goods.category.parent.id = pid
                                    goods.categories = [goods.category]
                                    delete goods.category
                                    goods.images = goods.images.join(',')
                                    var promise = IGoods.save(JSON.stringify(goods))
                                    promise.then(function (_pid) {
                                        _pid = parseInt(_pid)
                                        $self.mongo.collection('ProductAttribute').insertOne({pid: _pid, attributes: goods.attributes})
                                        console.log('insert done one >>>')
                                    })
                                    //console.log('goods>>>>', goods)
                                }catch(err){
                                    console.log('there are an error for ', _file)
                                }
                            })
                        })
                    })
                })
            })
        })
        yield $self.render('success', {
            message: '插入数据成功哦'
        })
    })
}